Imports System.ComponentModel
Imports System.IO

Public Class MainFormKrypton

    Private currentUser As DatabaseDataSet.UserRow
    Private currentEmployee As DatabaseDataSet.EmployeeRow
    Private bIsEmployee As Boolean
    Private bIsEmployer As Boolean
    Private luceneManager As LuceneManager
    Private isEmployer As Boolean
    Private isEmployee As Boolean
    Private frmLogin As Form
    Private sMailStatus As String
    Private sPdfFilename As String
    Private iNumberOfPdf As Integer = 0

    '===============================================================
    ' OverRidden Constructor of MainForm
    '---------------------------------------------------------------
    'Purpose : Overides the constructor of MainForm for the purpose of
    '          passing arguments. The user who has been checked in 
    '          Login Form is shown in MyProfile tab. Uses the 
    '          UserBindingSource.
    '
    ' Author : John Paraskevopoulos, 5 December 2012
    '===============================================================
    Public Sub New(ByVal userRow As DatabaseDataSet.UserRow, ByRef lgnForm As Form)
        ' Lucene Manager created - indexing all job offers to Ram
        luceneManager = New LuceneManager

        ' For temination functionality
        frmLogin = lgnForm

        Me.currentUser = userRow
        InitializeComponent()
        Me.KryptonNavigator1.SelectedPage = KryptonPage3
        Me.RegistrationControlKrypton1.UserBindingSource.DataSource = currentUser
        Me.FindJobOfferControlKrypton1.UserID = Me.currentUser.Item("UserID")
    End Sub

    Private Sub RegistrationControlKrypton1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles RegistrationControlKrypton1.Load
        isEmployee = False
        isEmployer = False
        FillEmployeesFields()
        FillEmployerFields()
        If (isEmployee <> True) Then
            KryptonNavigator1.Pages.Remove(KryptonPage1)
        End If

        If (isEmployer <> True) Then
            KryptonNavigator1.Pages.Remove(KryptonPage2)
        End If

        If Directory.Exists("temp") Then
            Directory.Delete("temp", True)
        End If
    End Sub

    '===============================================================
    ' Filling Employees Fields
    '---------------------------------------------------------------
    'Purpose : Fills the employee's fields if the current user is an
    '          employee himself. Uses the EmployeeBindingSource for
    '          the most of the controls, the DegreeBindingSource for 
    '          the DegreeCombobox and the Radio Buttns for the gender
    '
    ' Author : John Paraskevopoulos, 7 December 2012
    '===============================================================
    Private Sub FillEmployeesFields()
        Dim dtEmployee As DatabaseDataSet.EmployeeDataTable = New DatabaseDataSet.EmployeeDataTable
        Me.RegistrationControlKrypton1.EmployeeTableAdapter.FillByID(dtEmployee, Me.currentUser.Item(0))

        If dtEmployee.Count = 1 Then
            isEmployee = True
            Me.RegistrationControlKrypton1.chkEmployee.Checked = True
            Me.RegistrationControlKrypton1.EmployeeBindingSource.DataSource = dtEmployee

            'If user is an employee, keeping an instance
            Me.currentEmployee = dtEmployee.Rows(0)

            'Matches the degree of the employee
            Dim dtDegree As DatabaseDataSet.DegreeDataTable = New DatabaseDataSet.DegreeDataTable
            Me.RegistrationControlKrypton1.DegreeTableAdapter.Fill(dtDegree)
            Me.RegistrationControlKrypton1.DegreeBindingSource.DataSource = dtDegree
            Me.RegistrationControlKrypton1.cboDegree.SelectedValue = dtEmployee.Item(0).EmployeeDegreeID

            'Matches the gender of the employee
            If String.Compare(dtEmployee.Item(0).EmployeeGender, "M") = 0 Then
                Me.RegistrationControlKrypton1.rbMale.Checked = True
            ElseIf String.Compare(dtEmployee.Item(0).EmployeeGender, "F") = 0 Then
                Me.RegistrationControlKrypton1.rbFemale.Checked = True
            End If
        Else
            Me.RegistrationControlKrypton1.chkEmployee.Checked = False
        End If

    End Sub

    '===============================================================
    ' Filling Employers Fields
    '---------------------------------------------------------------
    'Purpose : Fills the employer's fields if the current user is an
    '          employer himself. Uses the EmployerBindingSource for
    '          the controls.
    '
    ' Author : John Paraskevopoulos, 7 December 2012
    '===============================================================
    Private Sub FillEmployerFields()
        Dim dtEmployer As DatabaseDataSet.EmployerDataTable = New DatabaseDataSet.EmployerDataTable
        Me.RegistrationControlKrypton1.EmployerTableAdapter.FillByID(dtEmployer, Me.currentUser.Item(0))

        If dtEmployer.Count = 1 Then
            isEmployer = True
            Me.RegistrationControlKrypton1.chkEmployer.Checked = True
            Me.RegistrationControlKrypton1.EmployerBindingSource.DataSource = dtEmployer
        Else
            Me.RegistrationControlKrypton1.chkEmployer.Checked = False
        End If
    End Sub

    '===============================================================
    ' Finding the matched offers 
    '---------------------------------------------------------------
    'Purpose : Gets the "right" offers for the current Employee.
    '          Offers depend on Employee's fields and selected 
    '          options. Uses an object of JOfferMatcher class.        
    '
    ' Author : John Paraskevopoulos, 12 December 2012
    '===============================================================
    Private Sub btnFindJobOffers_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnFindJobOffers.Click
        ' Flag for paint method
        Me.FindJobOfferControlKrypton1.setPaint()
        ' The values selected on the fly by the employee
        Dim userCity = Me.FindJobOfferControlKrypton1.cboCity.Text
        Dim userCountryID = Me.FindJobOfferControlKrypton1.cboCountry.SelectedValue
        Dim userMinFee = Convert.ToInt32(Me.FindJobOfferControlKrypton1.txtMinSalary.Text)
        Dim userTypeOfferID = Me.FindJobOfferControlKrypton1.cboJobType.SelectedValue

        ' Creating a new JOfferMatcher Object and getting the matching offers 
        Dim jOfferMatcher As JOfferMatcher = New JOfferMatcher(currentEmployee, userTypeOfferID, userCity, userCountryID, userMinFee)
        Dim dtOffers As DataTable = jOfferMatcher.getOffers

        If dtOffers.Rows.Count = 0 Then
            MessageBox.Show("There are not job offers matched to your searching senario. Sorry!")
            Return
        End If
        Me.FindJobOfferControlKrypton1.DataGridViewJobOffers.DataSource = dtOffers



        setFormatOfDataGrid()

        'Enable buttons: Export to Pdf, Send Mail, Send Employer Email
        Me.btnExportToPdf.Enabled = True
        Me.btnSendEmail.Enabled = True
        Me.FindJobOfferControlKrypton1.btnSendEmployerEmail.Enabled = True

    End Sub

    Private Sub btnConfirm_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnConfirm.Click
        Me.RegistrationControlKrypton1.ValidateChildren()
        If Not Me.RegistrationControlKrypton1.ValidateFields() Then
            Return
        End If

        UpdateUserData()
        CheckAndChangeEmployeeData()
        CheckAndChangeEmployerData()

        bIsEmployee = Me.RegistrationControlKrypton1.chkEmployee.Checked
        bIsEmployer = Me.RegistrationControlKrypton1.chkEmployer.Checked

        MessageBox.Show("Account updated!", "Registration", MessageBoxButtons.OK, MessageBoxIcon.Information)

    End Sub

    '===============================================================
    ' Updating User's Data
    '---------------------------------------------------------------
    'Purpose : Updates user's data in the database.          
    '
    ' Author : Chatzigeorgiou Konstantinos, 11 December 2012
    '===============================================================
    Private Sub UpdateUserData()
        Me.UserTableAdapter.Update(Me.RegistrationControlKrypton1.txtFirstName.Text, Me.RegistrationControlKrypton1.txtLastName.Text, _
                                   Me.RegistrationControlKrypton1.txtUsername.Text, Me.RegistrationControlKrypton1.txtPassword.Text, _
                                   Me.RegistrationControlKrypton1.txtEmail.Text, Me.currentUser.Item(0))
    End Sub

    '===============================================================
    ' Checking And Changing Employee's Data
    '---------------------------------------------------------------
    'Purpose : Checks if employee's data must be changed in the 
    '          database. If they must be changed, it chooses to inserts 
    '          or updates or deletes.
    '
    ' Author : Chatzigeorgiou Konstantinos, 11 December 2012
    '===============================================================
    Private Sub CheckAndChangeEmployeeData()
        If Me.RegistrationControlKrypton1.chkEmployee.Checked Then
            Dim gender As String = If(Me.RegistrationControlKrypton1.rbMale.Checked, "M", "F")
            Dim master As Boolean = If(Me.RegistrationControlKrypton1.chkMaster.Checked, True, False)
            Dim phd As Boolean = If(Me.RegistrationControlKrypton1.chkPhd.Checked, True, False)
            Dim army As Boolean = If(Me.RegistrationControlKrypton1.chkArmy.Checked, True, False)

            If Not bIsEmployee Then
                Me.EmployeeTableAdapter.Insert(Me.currentUser.Item(0), Convert.ToInt16(Me.RegistrationControlKrypton1.txtAge.Text), _
                                               gender, Me.RegistrationControlKrypton1.cboDegree.SelectedValue, master, phd, army, _
                                               Me.RegistrationControlKrypton1.cboForeignLanguage.SelectedItem)
                KryptonNavigator1.Pages.Insert(0, KryptonPage1)
            Else
                Me.EmployeeTableAdapter.Update(Me.RegistrationControlKrypton1.txtAge.Text, gender, Convert.ToInt16(Me.RegistrationControlKrypton1.cboDegree.SelectedValue), _
                                               master, phd, army, Me.RegistrationControlKrypton1.cboForeignLanguage.SelectedItem, Me.currentUser.Item(0))
            End If
        ElseIf Not Me.RegistrationControlKrypton1.chkEmployee.Checked And bIsEmployee Then
            If MessageBox.Show("Delete Employee?", "Delete", MessageBoxButtons.YesNo) = Windows.Forms.DialogResult.Yes Then
                Me.EmployeeTableAdapter.Delete(Me.currentUser.Item(0))
                KryptonNavigator1.Pages.Remove(KryptonPage1)
            Else
                Me.RegistrationControlKrypton1.chkEmployee.Checked = True
            End If
        End If
    End Sub

    '===============================================================
    ' Checking And Changing Employer's Data
    '---------------------------------------------------------------
    'Purpose : Checks if employer's data must be changed in the 
    '          database. If they must be changed, it chooses to inserts 
    '          or updates or deletes.
    '
    ' Author : Chatzigeorgiou Konstantinos, 11 December 2012
    '===============================================================
    Private Sub CheckAndChangeEmployerData()
        If Me.RegistrationControlKrypton1.chkEmployer.Checked And Not bIsEmployer Then
            Me.EmployerTableAdapter.Insert(Me.currentUser.Item(0), Me.RegistrationControlKrypton1.txtCompanyTitle.Text, _
                                           Me.RegistrationControlKrypton1.txtCompanyDescription.Text)
            KryptonNavigator1.Pages.Insert(1, KryptonPage2)
        ElseIf Me.RegistrationControlKrypton1.chkEmployer.Checked And bIsEmployer Then
            Me.EmployerTableAdapter.Update(Me.RegistrationControlKrypton1.txtCompanyTitle.Text, Me.RegistrationControlKrypton1.txtCompanyDescription.Text, _
                                           Me.currentUser.Item(0))
        ElseIf Not Me.RegistrationControlKrypton1.chkEmployer.Checked And bIsEmployer Then
            If MessageBox.Show("Delete Employer?", "Delete", MessageBoxButtons.YesNo) = Windows.Forms.DialogResult.Yes Then
                Me.EmployerTableAdapter.Delete(Me.currentUser.Item(0))
                KryptonNavigator1.Pages.Remove(KryptonPage2)
            Else
                Me.RegistrationControlKrypton1.chkEmployee.Checked = True
            End If
        End If
    End Sub

    Private Sub MainForm_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
        'TODO: This line of code loads data into the 'DatabaseDataSet.Employer' table. You can move, or remove it, as needed.
        Me.EmployerTableAdapter.Fill(Me.DatabaseDataSet.Employer)
        'TODO: This line of code loads data into the 'DatabaseDataSet.Employee' table. You can move, or remove it, as needed.
        Me.EmployeeTableAdapter.Fill(Me.DatabaseDataSet.Employee)
        'TODO: This line of code loads data into the 'DatabaseDataSet.User' table. You can move, or remove it, as needed.
        Me.UserTableAdapter.Fill(Me.DatabaseDataSet.User)

        Me.RegistrationControlKrypton1.txtUsername.Enabled = False

        bIsEmployee = Me.RegistrationControlKrypton1.chkEmployee.Checked
        bIsEmployer = Me.RegistrationControlKrypton1.chkEmployer.Checked

        Dim degreeDataTable As New DatabaseDataSet.DegreeDataTable
        Me.RegistrationControlKrypton1.DegreeTableAdapter.Fill(degreeDataTable)
        Me.RegistrationControlKrypton1.DegreeBindingSource.DataSource = degreeDataTable
    End Sub

    '===============================================================
    ' Inserting new Job Offer at the Database
    '---------------------------------------------------------------
    'Purpose : If the current user is an employer he can add a new 
    '          a new Job Offer.
    '
    ' Author : Chris Tsolakis, 12 December 2012
    '===============================================================
    Private Sub btnAddJobOffer_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnAddJobOffer.Click
        Me.JobOfferControlKrypton1.ValidateChildren()
        If Not Me.JobOfferControlKrypton1.ValidateFields() Then
            Return
        End If

        Dim response As Integer = _
                  MessageBox.Show( _
                  "Do you want to add the new Job Offer?", _
                  "Changes have been made", _
                  MessageBoxButtons.YesNo, _
                  MessageBoxIcon.Warning)

        If response = DialogResult.Yes Then
            Me.JobOfferControlKrypton1.JobOfferTableAdapter.Insert(Me.JobOfferControlKrypton1.cboDegree.SelectedValue, Convert.ToInt16(Me.JobOfferControlKrypton1.nmrUpDwnDegree.Value), _
                                                 Me.JobOfferControlKrypton1.chkMaster.Checked, Convert.ToInt16(Me.JobOfferControlKrypton1.nmrUpDwnMaster.Value), _
                                                 Me.JobOfferControlKrypton1.chkPhd.Checked, Convert.ToInt16(Me.JobOfferControlKrypton1.nmrUpDwnPhd.Value), _
                                                 Me.JobOfferControlKrypton1.cboForeignLanguage.Text, Convert.ToInt16(Me.JobOfferControlKrypton1.nmrUpDwnForeignLanguage.Value), _
                                                 Me.JobOfferControlKrypton1.chkArmy.Checked, Convert.ToInt16(Me.JobOfferControlKrypton1.nmrUpDwnArmy.Value), _
                                                 Me.JobOfferControlKrypton1.cboJobType.SelectedValue, Convert.ToInt16(Me.JobOfferControlKrypton1.nmrUpDwnJobType.Value), _
                                                 Me.JobOfferControlKrypton1.txtDescription.Text, Convert.ToDouble(Me.JobOfferControlKrypton1.txtSalary.Text), _
                                                 Me.JobOfferControlKrypton1.cboCity.Text, Convert.ToInt16(Me.JobOfferControlKrypton1.cboCountry.SelectedValue), currentUser.Item(0))

            MessageBox.Show("Your Job Offer was saved", _
                  "Job Offer", MessageBoxButtons.OK)

            ClearAllControls()

            ' Update luceneManager - update indexing
            Me.luceneManager = New LuceneManager
        End If
    End Sub

    '===============================================================
    ' Clearing the controls after inserting new Job Offer at Database
    '---------------------------------------------------------------
    'Purpose : After Inserting a new Job Offer at the Database all
    '          the controls automatically clears so a new Job Offer
    '          can be added without closing the programm
    '
    ' Author : Chris Tsolakis, 12 December 2012
    '===============================================================

    Private Sub ClearAllControls()

        For Each Item As Control In Me.JobOfferControlKrypton1.TableLayoutPanel1.Controls

            If TypeOf Item Is TextBox Then
                Item.Text = String.Empty
            End If

            Me.JobOfferControlKrypton1.txtSalary.Text = 0

            If TypeOf Item Is ComboBox Then
                Dim cbo As ComboBox = Item
                cbo.SelectedIndex = 0
            End If

            If TypeOf Item Is CheckBox Then
                Dim chk As CheckBox = Item
                chk.Checked = False
            End If

            If TypeOf Item Is TrackBar Then
                Dim trckBr As TrackBar = Item
                trckBr.Value = 0
            End If

            If TypeOf Item Is NumericUpDown Then
                Dim nmrUpDwn As NumericUpDown = Item
                nmrUpDwn.Value = 0
            End If
        Next
    End Sub

    '===============================================================
    ' Job Offer results export to Pdf document
    '---------------------------------------------------------------
    'Purpose : Export DataGridView in FindJobOffers Control to Pdf
    '          document with the use of pdf object from PdfManager
    '          Class
    '
    ' Author : Kwtteras Dimitrios, 4 January 2013
    '===============================================================

    Private Sub btnExportToPdf_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnExportToPdf.Click

        ' Checking if there are no results
        If (Me.FindJobOfferControlKrypton1.DataGridViewJobOffers.Rows.Count = 0) Then
            MessageBox.Show("There are no results to print!")
            Return
        End If

        SaveFileDialog.Filter = "pdf (*.pdf)|*.pdf"
        SaveFileDialog.ShowDialog()

        If SaveFileDialog.FileName = "" Then
            MsgBox("Enter Filename to create PDF")
            Exit Sub
        Else
            Dim pdf = New PdfManager(FindJobOfferControlKrypton1)
            pdf.ExportDataToPDFTable(SaveFileDialog.FileName)
            MsgBox("PDF Created Successfully")
        End If

    End Sub

    '===============================================================
    ' Sending email message
    '---------------------------------------------------------------
    'Purpose : Sends an email message which has an attachment, a pdf
    '          file with the results of the 'Find a job' search. 
    '
    ' Author : Chatzigeorgiou Konstantinos, 4 January 2013
    '===============================================================
    Private Sub btnSendEmail_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnSendEmail.Click

        ' Checking if there are no results
        If (Me.FindJobOfferControlKrypton1.DataGridViewJobOffers.Rows.Count = 0) Then
            MessageBox.Show("As much i enjoy seeing my inbox full, there are no results to send!")
            Return
        End If

        btnSendEmail.Enabled = False

        Directory.CreateDirectory("temp")
        sPdfFilename = "temp/Results" + iNumberOfPdf.ToString + ".pdf"
        iNumberOfPdf += 1

        Dim pdf = New PdfManager(FindJobOfferControlKrypton1)
        pdf.ExportDataToPDFTable(sPdfFilename)

        Dim bgWorker As New BackgroundWorker
        AddHandler bgWorker.DoWork, AddressOf EmailBackgroundWorker_DoWork
        AddHandler bgWorker.RunWorkerCompleted, AddressOf EmailBackgroundWorker_RunWorkerCompleted
        bgWorker.RunWorkerAsync()
    End Sub

    Private Sub EmailBackgroundWorker_DoWork(ByVal sender As System.Object, ByVal e As System.ComponentModel.DoWorkEventArgs)
        Dim mailManager As MailManager = New MailManager(My.Settings.MailServerSettings)
        Dim time As DateTime = DateTime.Now

        sMailStatus = mailManager.SendEmailWithAttachment(Me.currentUser.UserEmail, "Find a job - Results", "Date: " + time.ToString, sPdfFilename)
    End Sub

    Private Sub EmailBackgroundWorker_RunWorkerCompleted(ByVal sender As System.Object, ByVal e As System.ComponentModel.RunWorkerCompletedEventArgs)
        MessageBox.Show(sMailStatus)
        btnSendEmail.Enabled = True
    End Sub

    '===============================================================
    ' Searching Job Offers via Lucene Manager
    '---------------------------------------------------------------
    ' Purpose : Finds the job offers using lucene manager according to 
    '           the keywords in txtLuceneKeywords
    '         
    ' Author : John Paraskevopoulos, 5 January 2013
    '===============================================================
    Private Sub btnLuceneSearch_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnLuceneSearch.Click
        If (txtLuceneKeywords.Text = "") Then
            MessageBox.Show("Please enter one or more keywords for free text searching")
            Return
        End If
        ' Flag for paint method
        Me.FindJobOfferControlKrypton1.unsetPaint()
        Dim results As DataTable = Me.luceneManager.findOffers(Me.txtLuceneKeywords.Text)
        If results.Rows.Count = 0 Then
            MessageBox.Show("There are not job offers matched to your searching senario. Sorry!")
            Return
        End If

        Me.FindJobOfferControlKrypton1.DataGridViewJobOffers.DataSource = results
        setFormatOfDataGrid()
    End Sub

    '===============================================================
    ' MainForm close form event
    '---------------------------------------------------------------
    ' Purpose : Overides the close event of mainform form
    '           Terminates the program
    '
    ' Author : John Paraskevopoulos, 6 January 2013
    '===============================================================
    Private Sub MainForm_FormClosing(ByVal sender As System.Object, ByVal e As System.Windows.Forms.FormClosingEventArgs) Handles MyBase.FormClosing
        Me.frmLogin.Close()
    End Sub

    Private Sub setFormatOfDataGrid()
        'Setting the interface of the results
        For Each col In Me.FindJobOfferControlKrypton1.DataGridViewJobOffers.Columns
            If col.Name <> "JobOfferDescription" And col.Name <> "Rank" Then
                col.Visible = False
            End If
        Next

        Me.FindJobOfferControlKrypton1.DataGridViewJobOffers.ColumnHeadersVisible = False
        Me.FindJobOfferControlKrypton1.DataGridViewJobOffers.Columns("JobOfferDescription").Width = 400
        Me.FindJobOfferControlKrypton1.DataGridViewJobOffers.CellBorderStyle = DataGridViewCellBorderStyle.Sunken
        Me.FindJobOfferControlKrypton1.DataGridViewJobOffers.AutoSizeRowsMode = DataGridViewAutoSizeRowsMode.AllCells
        Me.FindJobOfferControlKrypton1.DataGridViewJobOffers.DefaultCellStyle.WrapMode = DataGridViewTriState.True
        Me.FindJobOfferControlKrypton1.DataGridViewJobOffers.ScrollBars = ScrollBars.None
    End Sub

    '===============================================================
    ' Log Out 
    '---------------------------------------------------------------
    ' Purpose : Log out from the Main Form and show of Log in Form
    '           so annother user can log in.
    '
    ' Author : Chris Tsolakis, 6 January 2013
    '===============================================================
    Private Sub KryptonNavigator1_TabClicked(ByVal sender As System.Object, ByVal e As ComponentFactory.Krypton.Navigator.KryptonPageEventArgs) Handles KryptonNavigator1.TabClicked
        If e.Item.Text.ToString = "Logout" Then
            MsgBox("Logout successfully!")
            frmLogin.Show()
            Me.Hide()
        End If
    End Sub
End Class